package com.xuebang.admin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xuebang.admin.dao.Finder;
import com.xuebang.admin.dao.Finder.Query;
import com.xuebang.admin.dao.Pagination;
import com.xuebang.admin.entity.Department;
import com.xuebang.admin.entity.Operator;
import com.xuebang.admin.entity.Position;
import com.xuebang.admin.mapper.OperatorMapper;
import com.xuebang.admin.web.Table;

@Service
@Transactional
public class OperatorService {
	private Logger logger = LoggerFactory.getLogger(OperatorService.class);

	@Inject
	private OperatorMapper operatorMapper;
	@Inject
	private OperatorGroupsService operatorGroupsService;
	@Inject
	private PasswordEncoder passwordEncoder;

	@Inject
	Finder finder;

	// 分页算法
	public Pagination<Operator> search(Table table, String searchStr, String departmentId) {
		String orderBy = table.getOrderBy();
		Query operatorQuery = finder.from("operators").where("status","A");
		if(searchStr!=null && !"".equals(searchStr)){
			operatorQuery.like("name", "%"+searchStr+"%");
		}
		if(departmentId!=null && !"".equals(departmentId)){
			Long departmentIdLong = Long.parseLong(departmentId);
			List<Position> positions = finder.from("positions").where("department_Id", departmentIdLong).all(Position.class);
			if(positions!=null && positions.size()>0){
				List<Long> positionIdList = new ArrayList<Long>();
				for(Position position:positions){
					positionIdList.add(position.getPositionId());
				}
				operatorQuery.in("position_Id", positionIdList.toArray());
			}else{
				operatorQuery.where("1!=1");
			}
		}
		
		Pagination<Operator> operators = operatorQuery.orderBy(orderBy).paginate(Operator.class, table.getPage());
		Iterator<Operator> iterator = operators.getData().iterator();
		while(iterator.hasNext()){
			Operator next = iterator.next();
			next=fetchProperties(next);
		}
		return operators;
	}

	public Operator fetchProperties(Operator operator) {
		if(operator==null){
			return null;
		}
		Long groupId = operator.getGroupId();
		operator.setOperatorGroups(operatorGroupsService.findById(groupId));
		Long positionId = operator.getPositionId();
		if(positionId!=null){
//			Position position = finder.find(Position.class,"positions", "position_Id", positionId);
//			Long departmentId = position.getDepartmentId();
//			if(departmentId!=null){
//				Department department = finder.find(Department.class, "Departments", "department_Id", departmentId);
//				position.setDepartment(department);
//			}
//			operator.setPosition(position);
		}
		return operator;
	}

	public Operator findById(Long id) {
		return this.fetchProperties(finder.find(Operator.class,"operators", "operator_Id", id));
	}
	
	public List<Operator> search(){
		
		List<Operator> operatorList = operatorMapper.search();
		return operatorList;
	}

	public void create(Operator operator) {
		String loginName = operator.getLoginName();
		Operator operatorTmp = operatorMapper.findByLoginName(loginName);
		if(operatorTmp!=null){
			throw new RuntimeException("账号"+loginName+"已存在！");
		}
		String cryptedPassword = passwordEncoder.encodePassword(
				operator.getPasswd(), operator.getLoginName());
		operator.setPasswd(cryptedPassword);
		operatorMapper.insertOperator(operator);
	}

	public void update(Operator operator) {
		if(operator.getPasswd()==null || "".equals(operator.getPasswd())){
			operatorMapper.updateOperatorExceptPasswd(operator);
		}else{
			String cryptedPassword = passwordEncoder.encodePassword(
					operator.getPasswd(), operator.getLoginName());
			operator.setPasswd(cryptedPassword);
			operatorMapper.updateOperator(operator);
		}
	}

	public void updateSelf(Operator operator) {
		Long operatorId = operator.getOperatorId();
		Operator operatorInDb = findById(operatorId);
		operatorInDb.setName(operator.getName());
		operatorInDb.setEmail(operator.getEmail());
		operatorInDb.setMobile(operator.getMobile());
		operatorInDb.setModifyDate(new Date());
		if(operator.getPasswd()==null || "".equals(operator.getPasswd())){
			operatorMapper.updateOperatorExceptPasswd(operatorInDb);
		}else{
			if(!operatorInDb.getPasswd().equals(passwordEncoder.encodePassword(
					operator.getOldPasswd(), operatorInDb.getLoginName()))){
				throw new RuntimeException("当前密码输入有误！");
			}
			String cryptedPassword = passwordEncoder.encodePassword(
					operator.getPasswd(), operatorInDb.getLoginName());
			operatorInDb.setPasswd(cryptedPassword);
			operatorMapper.updateOperator(operatorInDb);
		}
	}
	
	public Operator getOperatorInfo(String operatorId) {
		return operatorMapper.findById(Long.valueOf(operatorId));
	}

	public Operator login(String loginName, String password) {
		Operator operator = operatorMapper.findByLoginName(loginName);
		if (operator == null) {
			return null;
		}
		operator=this.fetchProperties(operator);
		String cryptedPassword = passwordEncoder.encodePassword(password,loginName);
		if (cryptedPassword.equals(operator.getPasswd())) {
			operator.setLastLoginDate(new Date());
			operatorMapper.updateOperator(operator);
			return operator;
		}

		return null;
	}

	public void delOperators(String operatorIds) {
		String[] operatorIdStr = operatorIds.split(",");
		if(operatorIdStr!=null && operatorIdStr.length>0){
			for(String operatorId:operatorIdStr){
				if(!operatorId.equals("")){
					operatorMapper.delOperator(Long.parseLong(operatorId));
				}
			}
		}
	}

}
